//定义路由 
import Vue from "vue";
import VueRouter from "vue-router";
// 把这段代码直接粘贴到router/index.js中的Vue.use(VueRouter)之前
const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function(location) {
  return originalPush.call(this, location).catch(err => {})
};
Vue.use(VueRouter)

//导入对应的路由组件
import Home from '@/views/Home'
import Search from '@/views/Search'

//配置路由规则
const routes = [
    { path: '/', redirect: '/home', },
    {
        path: '/home',
        meta: {
            isshowtanbar: true //meat 字段为路由元信息 给当前路由添加一些标记信息
        },
        component: Home, name: 'home',
        children: [{
            path: 'search', component: Search, name: 'search',
            meta: { isshowtanbar: false },
        }] //搜索页定义二级路由
    },
    { path: '/car', component: () => { return import('@/views/Car') }, name: 'car', meta: { isshowtanbar: true }, },
    { path: '/category', component: () => { return import('@/views/Category') }, name: 'category', meta: { isshowtanbar: true } },
    { path: '/topic', component: () => { return import('@/views/Topic') }, name: 'topic', meta: { isshowtanbar: true } },
    { path: '/user', component: () => { return import('@/views/User') }, name: 'user', meta: { isshowtanbar: true } },
    { path: '/productdetail', component: () => { return import('@/views/ProductDetail') }, name: 'productdetail', meta: { isshowtanbar: false } }
]

//创建路由实例对象
const router = new VueRouter({
    mode: 'history',
    routes
})

router.beforeEach((to, from, next) => {
    if (to.path == '/car') {
        const token = localStorage.getItem('token')
        if (token) {
            next()
        } else {
            Vue.prototype.$toast({
                type: 'fail',
                message: '请登录后查看购物车',
                durtion: 2000

            })
            setTimeout(() => {
                next('user')

            }, 200)



        }
    } else {
        next()
    }
})
//导出
export default router